import React, { useEffect, useState } from 'react'
import { Button, Table, message, Tag } from 'antd';
import axios from 'axios';

export default function AuditList(props) {
  const [auditNew, setAuditNew] = useState([])
  const { username } = JSON.parse(localStorage.getItem('token'))

  useEffect(() => {
    axios(`/news?author=${username}&auditState_ne=0&publishState_lte=1&_expand=category`).then(res => {
      // console.log(res)
      setAuditNew(res.data)

    })
  }, [username])

  // 撤销
  const revokeNew = (item) => {
    // console.log(item)
    // console.log(auditNew)
    setAuditNew(auditNew.filter(data => data.id !== item.id))
    axios.patch(`/news/${item.id}`, {
      auditState: 0
    }).then(res => {
      message.success('已转移至草稿箱')
    })
  }

  // 发布
  const publishNew = (item) => {
    axios.patch(`/news/${item.id}`, {
      publishState: 2,
      publishTime: Date.now()
    }).then(res => {
      message.success('发布成功')
      props.history.push('/publish-manage/published')
    })
  }

  // 更新
  const updateNew = (item) => {
    props.history.push(`/news-manage/update/${item.id}`)
  }

  // 表格数据
  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'title',
      render: (title, item) => <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (item) => item.title
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      render: (auditState) => {
        const colorList = ['', 'orange', 'green', 'red']
        const publishList = ['', '审核中', '已通过', '未通过']
        return <Tag color={colorList[auditState]}>{publishList[auditState]}</Tag>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          {
            item.auditState === 1 && <Button danger onClick={() => revokeNew(item)}>撤销</Button>
          }
          {
            item.auditState === 2 && <Button onClick={() => publishNew(item)}>发布</Button>
          }
          {
            item.auditState === 3 && <Button type='primary' onClick={() => updateNew(item)}>更新</Button>
          }
        </div>
      }
    },
  ];
  return (
    <div>
      <Table dataSource={auditNew} columns={columns} rowKey={item => item.id} pagination={{ pageSize: 5 }} />;
    </div>
  )
}
